package com.example.administrator.gpsstationbletool;

import android.app.AlertDialog;
import android.app.Dialog;
import android.bluetooth.BluetoothGattService;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.ContextThemeWrapper;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.utils.HexUtil;
import com.example.administrator.gpsstationbletool.adapter.CmdAdapter;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static com.example.administrator.gpsstationbletool.MainActivity.m_param;

public class YGSettingActivity extends AppCompatActivity {

    private CmdAdapter mCmdAdapter;
    private ResultAdapter resultAdapter;
    private Spinner mSpinnerCmd;
    private Spinner mSpinnerCmdValue;
    private TextView mTextCmdValue;
    private static BleDevice bleDevice;
    private static String serverUid = "0000ffe0-0000-1000-8000-00805f9b34fb";
    private static String chartUid  = "0000ffe1-0000-1000-8000-00805f9b34fb";

    private ListView listView_result;
    private boolean setCmdValue;

    public static void  setBleServerHandle(BleDevice bledev)
    {
        bleDevice = bledev;
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ygsetting);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

        toolbar.setTitle("翼戈基站设置向导");
        setSupportActionBar(toolbar);

        mCmdAdapter = new CmdAdapter(this);
        mCmdAdapter.setOnDeviceClickListener(new CmdAdapter.OnDeviceClickListener() {
            @Override
            public void onSendCmd(CmdAdapter.commandItem cmd) {
                String cmdstr = "$"+cmd.name+"="+cmd.value+"*\r\n";
                BleManager.getInstance().write(
                        bleDevice,
                        serverUid,
                        chartUid,
                        cmdstr.getBytes(),
                        new BleWriteCallback() {

                            @Override
                            public void onWriteSuccess(final int current, final int total, final byte[] justWrite) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        resultAdapter.addData( "write success" );
                                        resultAdapter.notifyDataSetChanged();
                                        listView_result.setSelection(resultAdapter.getCount()-1);
                                    }
                                });
                            }

                            @Override
                            public void onWriteFailure(final BleException exception) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        resultAdapter.addData(exception.toString());
                                        resultAdapter.notifyDataSetChanged();
                                        listView_result.setSelection(resultAdapter.getCount()-1);
                                    }
                                });
                            }
                        });

            }

            @Override
            public void onDelete(int index) {

            }

            @Override
            public void onItemEdit(int index) {
                showEditDlg(index);
            }
        });

        ListView listView_cmd = (ListView)  findViewById(R.id.list_cmd);
        listView_cmd.setAdapter(mCmdAdapter);
        listView_cmd.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            }
        });

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                    finish();
            }
        });

        mCmdAdapter.addCmd(new CmdAdapter.commandItem("wifiName",m_param.wifiName));
        mCmdAdapter.addCmd(new CmdAdapter.commandItem("wifiPasswd",m_param.wifiPasswd));
        mCmdAdapter.addCmd(new CmdAdapter.commandItem("serverIp",m_param.serverIp));
        mCmdAdapter.addCmd(new CmdAdapter.commandItem("serverPort",m_param.serverPort+""));
        mCmdAdapter.addCmd(new CmdAdapter.commandItem("baseLon",m_param.baseLon+""));
        mCmdAdapter.addCmd(new CmdAdapter.commandItem("baseLat",m_param.baseLat+""));
        mCmdAdapter.addCmd(new CmdAdapter.commandItem("baseAlt",m_param.baseAlt+""));
        mCmdAdapter.addCmd(new CmdAdapter.commandItem("baseCutoff",m_param.baseCutoff+""));
        mCmdAdapter.addCmd(new CmdAdapter.commandItem("command","paramSaveNow"));
        mCmdAdapter.notifyDataSetChanged();

        resultAdapter = new ResultAdapter(this);
        listView_result = (ListView)  findViewById(R.id.list_result);
        listView_result.setAdapter(resultAdapter);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CmdAdapter.commandItem nitem = new CmdAdapter.commandItem("wifiName","");
                int index = mCmdAdapter.addCmd(nitem);
                showEditDlg(index);
            }
        });

        BleManager.getInstance().notify(
                bleDevice,
                serverUid,
                chartUid,
                new BleNotifyCallback() {

                    @Override
                    public void onNotifySuccess() {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                //  addText(txt, "notify success");

                            }
                        });
                    }
                    @Override
                    public void onNotifyFailure(final BleException exception) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                resultAdapter.addData( exception.toString());
                                resultAdapter.notifyDataSetChanged();
                            }
                        });
                    }

                    @Override
                    public void onCharacteristicChanged(byte[] data) {
                        final String notif = new String(data);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                               resultAdapter.addData(notif);
                                resultAdapter.notifyDataSetChanged();
                                listView_result.setSelection(resultAdapter.getCount()-1);
                            }
                        });
                    }
                });
    }

    private  int SearchArray(String[] ay,String key)
    {
        for(int i = 0; i < ay.length;i++)
        {
            if(ay[i]==key)
                return i;

        }
        return  -1;
    }
    private  void showEditDlg(final int index){

        List<CmdAdapter.commandItem>cmditems =  mCmdAdapter.getCommandList();
        CmdAdapter.commandItem citem = cmditems.get(index);

        AlertDialog.Builder builder = new AlertDialog.Builder(
                new ContextThemeWrapper(this, R.style.qmui_dialog_wrap));
        View view = LayoutInflater.from(this).inflate(R.layout.paramedit_layout,null);  //关键语句1，你自定义的layout，所有layout哟

        String[] spinnerItems = {"wifiName","wifiPasswd","serverIp","serverPort","baseLon","baseLat","baseAlt","baseCutoff","command"};
        String[] cmdItems = {"gpsSetNow","wifiSetNow","paramSaveNow","systemResetNow"};
        mSpinnerCmd = (Spinner) view.findViewById(R.id.spinner);
        mSpinnerCmdValue = (Spinner) view.findViewById(R.id.spinner_cmd_value);

        mTextCmdValue = (TextView) view.findViewById(R.id.valueText);
        Button btnok = (Button)view.findViewById(R.id.buttonOK);
        Button btncancel = (Button)view.findViewById(R.id.buttonCancel);



        ArrayAdapter<String> adapterCmd = new ArrayAdapter<String>(
                YGSettingActivity.this, R.layout.paramitem_select,
                spinnerItems);
        adapterCmd.setDropDownViewResource(R.layout.paramitem_drop);
        mSpinnerCmd.setAdapter(adapterCmd);

        ArrayAdapter<String> adapterCmdValue = new ArrayAdapter<String>(
                YGSettingActivity.this, R.layout.paramitem_select,
                cmdItems);
        adapterCmdValue.setDropDownViewResource(R.layout.paramitem_drop);
        mSpinnerCmdValue.setAdapter(adapterCmdValue);
        builder.setView(view);  //关键语句2，令自定义view作为alertDialog的子view，此时

        mSpinnerCmd.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,int position, long id) {
                String data = (String)mSpinnerCmd.getItemAtPosition(position);//从spinner中获取被选择的数据
                if(data == "command")
                {
                    mTextCmdValue.setVisibility(View.GONE);
                    mSpinnerCmdValue.setVisibility(View.VISIBLE);
                }else
                {
                    mTextCmdValue.setVisibility(View.VISIBLE);
                    mSpinnerCmdValue.setVisibility(View.GONE);
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // TODO Auto-generated method stub
            }
        });
        mSpinnerCmdValue.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,int position, long id) {
                String data = (String)mSpinnerCmdValue.getItemAtPosition(position);//从spinner中获取被选择的数据
                mTextCmdValue.setText(data);
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // TODO Auto-generated method stub
            }
        });

        int si = SearchArray(spinnerItems,citem.name);
        mSpinnerCmd.setSelection(si);
        if(citem.name != "command")
        {
            mSpinnerCmd.setSelection(si);
            mTextCmdValue.setText(citem.value);
        }else
        {
            si = SearchArray(cmdItems,citem.value);
            mSpinnerCmdValue.setSelection(si);
        }

        final Dialog dialog = builder.create();
        dialog.show();

        btnok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name =  mSpinnerCmd.getSelectedItem().toString();
                CmdAdapter.commandItem citem = new CmdAdapter.commandItem(name,mTextCmdValue.getText().toString());
                mCmdAdapter.updateCmd(index,citem);
                mCmdAdapter.notifyDataSetChanged();
                dialog.dismiss();
            }
        });

        btncancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }


    private class ResultAdapter extends BaseAdapter {

        List<String> datalist;
        private Context context;
        LayoutInflater mInflater;

        public ResultAdapter(Context context) {
            this.context = context;
            this.datalist = new ArrayList<>();
            mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            return datalist.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            TextView view;
            if (convertView == null) {
                view = (TextView)mInflater.inflate(android.R.layout.simple_list_item_1, parent, false);
            } else {
                view = (TextView) convertView;
            }
            view.setText(datalist.get(position));
            view.setTextSize(15f);
            view.setGravity(Gravity.LEFT);

            return view;
        }
        public void addData(String linestr)
        {
            datalist.add(linestr);
        }

    }
}
